﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.ApplicationPages.Calendar.RecurrenceRule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindStyle.SPCalendar
{
    //TODO:refactor like Microsoft.SharePoint.ApplicationPages.Calendar.Exchange.RecurrenceType to support xml serialization
    public class Recurrence<T>
        where T : Pattern.IPattern, new()
    {
        public T Pattern { get; set; }
        public DateRange DateRange { get; set; }

        public Recurrence()
        {
            this.Pattern = new T();
            this.DateRange = new DateRange();
        }

        public string ToXML(SPRegionalSettings regionalSettings)
        {
            return string.Format(@"
<recurrence><rule>
<firstDayOfWeek>{0}</firstDayOfWeek>
<repeat>{1}</repeat>
{2}
</rule></recurrence>",
              ((System.DayOfWeek)regionalSettings.FirstDayOfWeek).ToString().Substring(0, 2).ToLower(),
              this.Pattern.ToXML(),
              this.DateRange.ToXml(regionalSettings)).Replace("\r\n", string.Empty);
        }

        public void Read(Microsoft.SharePoint.SPListItem item, SPRegionalSettings regionalSettings)
        {
            this.DateRange.StartDate = ((DateTime)item[SPBuiltInFieldId.StartDate]).Date;

            if (item.Fields.Contains(SPBuiltInFieldId.RecurrenceData) && item[SPBuiltInFieldId.RecurrenceData] != null)
            {
                var recurrence = new RecurrenceRule(item[SPBuiltInFieldId.RecurrenceData].ToString());

                this.DateRange.End.FromRule(recurrence, regionalSettings);
                this.Pattern.FromRule(recurrence);
            }
        }
    }
}
